package org.istt.dao.hibernate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.istt.domain.TimeHoliday;
import org.istt.domain.TimeWeekend;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.MutableDateTime;

/**
 * @author NDTHO
 */
public class UtilsDaoHibernate {
	Log logger = LogFactory.getLog(UtilsDaoHibernate.class);
	
	public int getWorkingDays(DateTime fromdate, DateTime todate, List<TimeHoliday> timeHolidays, List<TimeWeekend> timeWeekends) {
		int result = 0;
		
		//period of time
		DateTime start = new DateMidnight().toDateTime();

		if(fromdate!=null) start = fromdate;
		
		//how many holidays are between the period of time 
		List<DateTime> lstDt = new ArrayList<DateTime>();
		for (TimeHoliday thday : timeHolidays) {
			if (thday.getRepeat()) {
				MutableDateTime mdt = new DateTime(thday.getHolidayDate()).toMutableDateTime();
				mdt.setYear(start.getYear());
				lstDt.add(mdt.toDateTime());
			} else {
				lstDt.add(new DateTime(thday.getHolidayDate()));
			}
		}
		
		int[] dow = new int[]{DateTimeConstants.MONDAY, 
								DateTimeConstants.TUESDAY, 
								DateTimeConstants.WEDNESDAY, 
								DateTimeConstants.THURSDAY, 
								DateTimeConstants.FRIDAY, 
								DateTimeConstants.SATURDAY,
								DateTimeConstants.SUNDAY}; 
		List<Integer> dayOffs = new ArrayList<Integer>();
		for (TimeWeekend tw : timeWeekends) {
			for (int i = 0; i < dow.length; i++) {
				if (dow[i] == tw.getDay_id()) {
					dayOffs.add(dow[i]);
				}
			}
		}
		
		Collections.sort(dayOffs);
		
		
		DateTime tmp = start;
		for (;true;) {
			if(todate.getDayOfWeek() == tmp.getDayOfWeek() && todate.getDayOfMonth() == tmp.getDayOfMonth() && todate.getMonthOfYear() == tmp.getMonthOfYear())
				break;
			
			tmp = tmp.plusDays(1);
			System.out.print("tmp = " + tmp.toString("dd/MM/yyyy") + " " + tmp.toString("E"));
			
			boolean dayOffInTheWeek = false;
			boolean dayOffInTheHoliday = false;
			//day of week
			for (Integer dayOff : dayOffs) {
				if (tmp.getDayOfWeek() == dayOff) {
					//System.out.print(" ########## tmp.getDayOfWeek() == dayOff : " + (tmp.getDayOfWeek() == dayOff));
					dayOffInTheWeek = true;
					break;
				}
			}
			
			//day, month
			for (DateTime dt : lstDt) {
				if (dt.getDayOfMonth() == tmp.getDayOfMonth() && dt.getMonthOfYear() == tmp.getMonthOfYear()) {
					dayOffInTheHoliday = true;
				}
			}
			
			if (!dayOffInTheWeek && !dayOffInTheHoliday) result++;
			
 		}
		
		return result;
	}
}
